package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import com.atguigu.lease.common.exception.LeaseException;
/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    // 通用 mapper 实现分页查询
    @Autowired
    private RoomInfoMapper roomInfoMapper;

    // 回显信息进行修改
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private AttrValueMapper attrValueMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;


    // 保存或更新房间信息(有可能批量添加使用通用Service的saveBatch()方法)
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    // 以上都是外键表
    @Autowired
    private GraphInfoService graphInfoService;


    // 查询租约表里面的房间状态 看看是否删除房间信息
    @Autowired
    private LeaseAgreementMapper leaseAgreementMapper;

    @Override
    public IPage<RoomItemVo> getpageRoomItemByQuery(IPage<RoomItemVo> ipage, RoomQueryVo queryVo) {
        return roomInfoMapper. getpageRoomItemByQuery(ipage, queryVo);
    }


    // 有可能批量添加 使用通用Service的saveBatch()
    @Override
    public void saveOrUpdateRoom(RoomSubmitVo roomSubmitVo) {
        // 1- 判断房间Id是否存在 来判断对房间信息保存或者修改
        boolean isUpdate = roomSubmitVo.getId() != null;
        // 保存或者修改房间的基本信息
        this.saveOrUpdate(roomSubmitVo);  //this 当前类 roomInfoService

        // 2- 若为更新操作(Id存在) 则先删除与Room相关的各项信息列表
        if (isUpdate){
            // 删除 原有的房间配套信息
            roomFacilityService.remove(new LambdaQueryWrapper<RoomFacility>().eq(RoomFacility::getRoomId, roomSubmitVo.getId()));
            // 删除 原有的房间标签信息
            roomLabelService.remove(new LambdaQueryWrapper<RoomLabel>().eq(RoomLabel::getRoomId, roomSubmitVo.getId()));
            // 删除 原有的房间支付方式信息
            roomPaymentTypeService.remove(new LambdaQueryWrapper<RoomPaymentType>().eq(RoomPaymentType::getRoomId, roomSubmitVo.getId()));
            // 删除 原有的可选租期信息
            roomLeaseTermService.remove(new LambdaQueryWrapper<RoomLeaseTerm>().eq(RoomLeaseTerm::getRoomId,roomSubmitVo.getId()));
            // 删除 原有的房间属性信息
            roomAttrValueService.remove(new LambdaQueryWrapper<RoomAttrValue>().eq(RoomAttrValue::getRoomId,roomSubmitVo.getId()));
            // 删除 原有的房间图片信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType, roomSubmitVo.getId()).eq(GraphInfo::getItemType, ItemType.ROOM));
        }

        // 3- 填加房间关联的信息
        // 3.1 保存新的房间配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds(); // getFacilityInfoIds() 前端传过来的配套id列表
        if (!CollectionUtils.isEmpty(facilityInfoIds)) { // 用于判断一个集合是否为空,如果集合为空，isEmpty返回true；否则返回false。
            // 把每个roomFacility对象存到 集合中 一次性往数据库添加
            List<RoomFacility> roomFacilityList = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                // 把配套list集合中取出每一个配套对象 一个配套facilityInfoId 对应 一个房间的roomSubmitVo.getId() 存到roomFacility对象中
                RoomFacility roomFacility = RoomFacility.builder().roomId(roomSubmitVo.getId()).facilityId(facilityInfoId).build();
                roomFacilityList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityList);
        }

        // 3.2 保存新的房间标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds(); //getLabelInfoIds() 前端传过来的标签id列表
        if(!CollectionUtils.isEmpty(labelInfoIds)){
            ArrayList<RoomLabel> roomLabelList = new ArrayList<>();
            for (Long labelInfoId : labelInfoIds){
                RoomLabel roomLabel = RoomLabel.builder().roomId(roomSubmitVo.getId()).labelId(labelInfoId).build();
                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }

        // 3.3 保存新的房间支付方式信息
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if(!CollectionUtils.isEmpty(paymentTypeIds)){
            ArrayList<RoomPaymentType> roomPaymentTypeList = new ArrayList<>();
            for (Long paymentTypeId : paymentTypeIds){
                RoomPaymentType roomPaymentType = RoomPaymentType.builder().roomId(roomSubmitVo.getId()).paymentTypeId(paymentTypeId).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        // 3.4 保存新的房间可选租期信息
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if(!CollectionUtils.isEmpty(leaseTermIds)){
            ArrayList<RoomLeaseTerm> roomLeaseTermList = new ArrayList<>();
            for (Long leaseTermId : leaseTermIds){
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().roomId(roomSubmitVo.getId()).leaseTermId(leaseTermId).build();
                roomLeaseTermList.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }

        // 3.5 保存新的房间属性信息
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            ArrayList<RoomAttrValue> roomAttrValueList = new ArrayList<>();
            for (Long attrValueId : attrValueIds){
                RoomAttrValue roomAttrValue = RoomAttrValue.builder().roomId(roomSubmitVo.getId()).attrValueId(attrValueId).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValueList);
        }
        // 3.6 保存新的房间图片信息
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfos = new ArrayList<>();
            for (GraphVo graphVo : graphVoList){
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfo.setItemType(ItemType.ROOM);

                String url = graphVo.getUrl();
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                graphInfo.setUrl(url);
                graphInfo.setName(graphVo.getUrl());

                graphInfos.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfos);
        }
    }


    // 根据房间id 回显信息 （修改）
    @Override
    public RoomDetailVo getRoomDetailById(Long id) { // 房间：id
        // 查询到的房间以及房间相关的信息对象
        RoomDetailVo roomDetailVo = new RoomDetailVo();

        // 查询 房间的基本信息  this RoomInfoService
        RoomInfo roomInfo = this.getById(id);

        // 房间所属房间的公寓信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId()); // 所属房间里面有所属公寓的id
        // 查看所属房间 图片信息
       List<GraphVo> graphVoList = graphInfoMapper.selectListByApartmentId(id, ItemType.ROOM); //公寓/房间通用
       //  查看所属房间 属性信息
       List<AttrValueVo> attrValueVoList= attrValueMapper.selectListByRoomId(id);
       // 查看所属房间 配套信息
       List<FacilityInfo> facilityInfoList= facilityInfoMapper.selectListByRoomId(id);
       // 查看所属房间 标签信息
       List<LabelInfo> labelInfoList= labelInfoMapper.selectListByRoomId(id);
       // 查看所属房间 支付方式信息
       List<PaymentType> paymentTypeList= paymentTypeMapper.selectListByRoomId(id);
       // 查看所属房间 租期信息
       List<LeaseTerm> leaseTermList= leaseTermMapper.selectListByRoomId(id);

        // 赋值 roomDetailVo 各属性
        BeanUtils.copyProperties(roomInfo, roomDetailVo); //roomDetailVo和roomInfo是继承关系 对象属性对拷
        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);

        // 返回roomDetailVo对象
        return roomDetailVo;
    }


    // 根据房间id 删除房间信息
    @Override
    public void removeByRoomId(Long id) {
        LeaseAgreement leaseAgreement = leaseAgreementMapper.selectOne(new LambdaQueryWrapper<LeaseAgreement>().eq(LeaseAgreement::getRoomId, id).in(LeaseAgreement::getStatus, 2, 5));
        if (leaseAgreement != null) { // 房间已经被出租 抛异常
            throw new LeaseException(555,"房间已经被出租，暂时不能删除");
        }
        this.removeById(id); // 如果不存在直接删除房间信息

        // 删除房间相关信息
        //2.删除graphInfoList
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        graphQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphQueryWrapper);

        //3.删除attrValueList
        LambdaQueryWrapper<RoomAttrValue> attrQueryWrapper = new LambdaQueryWrapper<>();
        attrQueryWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(attrQueryWrapper);

        //4.删除facilityInfoList
        LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(facilityQueryWrapper);

        //5.删除labelInfoList
        LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(labelQueryWrapper);

        //6.删除paymentTypeList
        LambdaQueryWrapper<RoomPaymentType> paymentQueryWrapper = new LambdaQueryWrapper<>();
        paymentQueryWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(paymentQueryWrapper);

        //7.删除leaseTermList
        LambdaQueryWrapper<RoomLeaseTerm> termQueryWrapper = new LambdaQueryWrapper<>();
        termQueryWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(termQueryWrapper);
    }

}




